var dataDao = require('../dao/dataDao');

var upyunService = require('../../services/upyunService');
var uploadPath = require('../../config/uploadConfig');
var request = require('request');
var crypto = require('crypto');
var uuid = require('node-uuid');
var qs = require('querystring');
var fs = require('fs');
var signInfo, timestamp = Date.now();
//var signatureDao = require('../../temper/dao/signatureDao');

// 签证js
exports.getSign = function(criteria, cb) {
	var get = function() {
		var content = qs.stringify(criteria);
		request('https://api.weixin.qq.com/cgi-bin/token?'+ content, function(err, res, body) {
			if(err) {
				return cb(err);
			}

			var token = JSON.parse(body);
			var url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + token.access_token + '&type=jsapi';
			request(url, function(err, res, body) {
				if(err) 
					return cb(err);

				body = JSON.parse(body);
				if(body.errcode !== 0) 
					return cb({
						msg: body.errmsg,
						data: 'dataService 38'
					})

				var sign = {
					jsapi_ticket: body.ticket,
					noncestr: Math.random().toString(36).substr(2),
					timestamp: (Date.now()+'').substring(0, 10),
					url: criteria.url
				}

				var sha1 = function(str) {
					var md5sum = crypto.createHash('sha1');
					md5sum.update(str, 'utf8');
					str = md5sum.digest('hex');
					return str;
				}

				sign.signature = sha1(decodeURIComponent(qs.stringify(sign)));
				sign.appid = criteria.appid;
				sign.token = token.access_token;
				sign.url = criteria.url;
				sign.createAt = new Date();
				sign.id = uuid.unparse(uuid.v4(null, new Buffer(32), 0));
				signInfo = sign;
				timestamp = Date.now();
				dataDao.signature(signInfo, function(err, doc) {
					if(err) {
						cb(err);
					} else {
						dataDao.getLast(function(err, doc) {
							cb(err, doc[0]);
						})
					}
				})
			})
		})
	}
	dataDao.getLast(function(err, signArr) { // 获取最新签证
		if(err) {
			cb(err);
		} else {
			var signInfo = signArr[0];
			if(!signInfo) { // 签证不存在
				get()
			} else {
				var temp = Date.now()/1000 - signInfo.timestamp;
				if((temp>=3600)||(criteria.url!==signInfo.url)) { //签证超时或者签证地址与config冲突
					get();
				} else{
					cb(err, signInfo)
				}
			}
		}
	});
}

//下载图片
exports.downloadWXImage=function(businessid,images,spotid,callback){
	console.log(images)
	console.log("测试1")
	guihuaDao.findWxConfig(spotid,function(err,config){
		dataDao.select(config.payappid,function(err, signArr) {
			console.log(signArr)
			console.log(err)
			if(err) {
				return callback(err);
			} else if(signArr.length>0){
				src = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=' + signArr[0].token + '&media_id=';
				var dest = uploadPath['1004']['remote'] + '/' + businessid; // 目的地
				upyunService.pushWXPic(images, dest, src, function(err, data) {
					console.log(err)
					console.log(data)
					if(err) {
						callback(err);
					} else {
						callback(err, data);
					}
				})
			} else {
				callback({msg: '签证不存在，publishTemper Error'})
			}
		});
	});
}

// new 签证
exports.getSignature = function(spotid,cb) {
	dataDao.getSignature(spotid,function(err, docs) {
		cb(err, docs[0])
	})
}

// token 生成签证
exports.getToken = function(spotid,url, cb) {
	dataDao.getSignature(spotid,function(err, docs) {
		if(err) {
			return cb(err)
		}
		var doc = docs[0];
		// console.log(doc)
		var sign = {
			jsapi_ticket: doc.jsapi_ticket,
			noncestr: Math.random().toString(36).substr(2),
			timestamp: (Date.now()+'').substring(0, 10),
			url: url
		}
		var sha1 = function(str) {
			var md5sum = crypto.createHash('sha1');
			md5sum.update(str, 'utf8');
			str = md5sum.digest('hex');
			return str;
		}
		sign.signature = sha1(decodeURIComponent(qs.stringify(sign)));
		sign.appid = doc.appid;
		// console.log(sign);
		cb(err, sign);
	})
}

// base64
exports.base64 = function (base64Data, cb) {
	var fileName = 'img'+ new Date().getTime() +'.jpg';
	fs.writeFile('./uploads/code/'+ fileName, base64Data, function (err) {
		if(err) return cb(err);
		var dest = uploadPath['1004']['remote'];
		upyunService.upImgToUpyun(fileName, dest, function (err , data) {
			cb(err, data);
		})
	})
}


exports.getWxCodeList=function(ll,callback){
	dataDao.getWxCodeList(function(err, docs) {
		callback(err, docs)
	})
}

/**
 * 根据公众号授权openid去查询用户关注公众号的openid
 * @param userid
 * @param callback
 */
exports.findUserGZHOpenid=function(userid,callback){
	dataDao.findUserUnoidByUserid(userid,function(err,unionid){
		//console.log(unionid);
		if(unionid.eyouopenid){//新授权匹配方式
			callback(err,[{appid:"wx928dce38089037ba",openid:unionid.eyouopenid}]);//
		}else{
			dataDao.findEyouOpenid(unionid,"wx928dce38089037ba",function(err,openid){
				callback(err,openid);
			})
		}
	})
}
//var signatureConfig = require('../../config/wxSignature');
//console.log(qs.stringify(signatureConfig))

//加密
var sha1 = function(str) {
	var md5sum = crypto.createHash('sha1');
	md5sum.update(str, 'utf8');
	str = md5sum.digest('hex');
	return str;
}
/**
 * 获取淳璞旅游公众号的签证
 * @param config
 * @param cb
 */
exports.cpSignature = function (config, cb) {
	var content = qs.stringify(config);
	var signature = {};
	var step = {
		access_token: function (data) {
			return new Promise(function (resolve, reject) {
				var url = 'https://api.weixin.qq.com/cgi-bin/token?'+ content;
				request(url, function (err, res, body) {
					if(err) return reject(err);
					var body = JSON.parse(body);
					signature.access_token = body.access_token;
					resolve();
				})
			})
		},
		jsapi_ticket: function () {
			var url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+ signature.access_token +'&type=jsapi'
			return new Promise(function (resolve, reject) {
				request(url, function (err, res, body) {
					if(err) return reject(err);

					body = JSON.parse(body);
					if(body.errcode !== 0)
						return reject({
							success: 1,
							msg: body.errmsg
						})

					var sign = {
						jsapi_ticket: body.ticket,
						noncestr: Math.random().toString(36).substr(2),
						timestamp: (Date.now()+'').substring(0, 10),
						url: 'http://www.chinayolo.com/index.html?id=AT009'
					};

					sign.signature = sha1(decodeURIComponent(qs.stringify(sign)));
					sign.appid = config.appid;
					sign.token = signature.access_token;
					sign.url = config.url;
					sign.createAt = new Date();
					sign.id = uuid.unparse(uuid.v4(null, new Buffer(32), 0));
					return resolve(sign);
				})
			})
		},
		save_signature: function (sign) {
			return new Promise(function (resolve, reject) {
				dataDao.saveCPSignature(sign, function (err, data) {
					if(err) return reject(err);
					else resolve(sign);
				})
			})
		}
	};

	step.access_token().then(function () {
		return step.jsapi_ticket();
	}).then(function (sign) {
		return step.save_signature(sign);
	}).then(function (sign) {
		return cb(null, sign)
	}).catch(function (err) {
		if(err) return cb(err);
	})
}

/**
 * 获取签证票据
 * @param url
 * @param cb
 */
exports.getTicket = function (url,spotid, cb) {
	dataDao.getSignature(spotid,function (err, data) {
		//console.log(spotid);
		if(err) return cb(err);
		var sign = {
			jsapi_ticket: data.jsapi_ticket,
			noncestr: data.noncestr,
			timestamp: data.timestamp,
			url: url
		}
		data.signature = sha1(decodeURIComponent(qs.stringify(sign)));
		//console.log(sign,data)
		cb(err, data);
	})
}


exports.saveLastOpenid=function(openid,count){
	var obj={
		id:uuid.unparse(uuid.v4(null, new Buffer(32), 0)),
		openid:openid,
		usernum:count,
		createAt:new Date(),
		status:1
	}
	dataDao.saveLastOpenid(obj)
}

exports.findNextOpenid=function(callback){
	dataDao.findNextOpenid(function(err,data){
		callback(err,data);
	})
}


exports.findUserByOpenid=function(openid,appid,callback){
	dataDao.findUserByOpenid(openid,appid,function(err,data){
		callback(err,data);
	})
}